"""星座时-空分析系统 - 主入口点"""

import sys
import argparse
import numpy as np
from astropy import units as u
from astropy.time import Time, TimeDelta
from poliastro.bodies import Earth
from poliastro.twobody import Orbit
from poliastro.examples import iss
from poliastro.frames import Planes


from satellite import Satellite, SatelliteConstellation, Sensor, SensorType
from target import GroundTarget, GroundTargetGroup
from access import AccessCalculator
from propagator import PropagationMethod
from visualization import ConstellationVisualizer


def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description="星座时-空分析系统")
    
    # 添加参数
    parser.add_argument("--satellites", type=int, default=6,
                        help="星座中的卫星数量")
    parser.add_argument("--altitude", type=float, default=500,
                        help="卫星轨道高度(km)")
    parser.add_argument("--inclination", type=float, default=60,
                        help="卫星轨道倾角(度)")
    parser.add_argument("--days", type=float, default=1.0,
                        help="模拟时间长度(天)")
    parser.add_argument("--targets", type=str, default="北京,上海,广州",
                        help="目标城市，用逗号分隔")
    parser.add_argument("--step", type=float, default=30.0,
                        help="时间步长(秒)")
    parser.add_argument("--min-elevation", type=float, default=5.0,
                        help="最小仰角(度)")
    parser.add_argument("--use-iss", action="store_true",
                        help="使用国际空间站轨道作为示例")
    parser.add_argument("--plane", type=str, default="BODY_FIXED",
                        choices=["EARTH_EQUATOR", "EARTH_ECLIPTIC", "BODY_FIXED"],
                        help="参考平面: EARTH_EQUATOR, EARTH_ECLIPTIC, BODY_FIXED")
    
    return parser.parse_args()


def main():
    """主函数"""
    # 解析命令行参数
    args = parse_arguments()
    
    # 设置当前时间
    current_time = Time.now()
    
    # 根据参数选择参考平面
    if args.plane == "EARTH_EQUATOR":
        plane = Planes.EARTH_EQUATOR
    elif args.plane == "EARTH_ECLIPTIC":
        plane = Planes.EARTH_ECLIPTIC
    else:
        plane = Planes.BODY_FIXED
    
    # 创建星座
    if args.use_iss:
        # 使用国际空间站轨道作为示例
        constellation = SatelliteConstellation("ISS星座")
        satellite = Satellite("ISS", iss)
        optical_sensor = Sensor("光学相机", SensorType.OPTICAL, 45, 30)
        satellite.add_sensor(optical_sensor)
        satellite.set_propagation_method(PropagationMethod.J2)
        constellation.add_satellite(satellite)
    else:
        # 创建自定义星座
        constellation = SatelliteConstellation("LEO星座")
        
        # 计算轨道半长轴
        a = Earth.R + args.altitude * u.km
        
        # 创建卫星
        for i in range(args.satellites):
            # 计算升交点赤经
            raan = i * (360.0 / args.satellites) * u.deg
            
            # 创建轨道
            orbit = Orbit.circular(
                Earth,
                a,
                args.inclination * u.deg,
                raan,
                epoch=current_time,
                plane=plane
            )
            
            # 创建卫星
            satellite = Satellite(f"LEO-{i+1}", orbit)
            
            # 添加传感器
            optical_sensor = Sensor("光学相机", SensorType.OPTICAL, 45, 30)
            satellite.add_sensor(optical_sensor)
            
            # 设置传播方法
            satellite.set_propagation_method(PropagationMethod.J2)
            
            # 添加到星座
            constellation.add_satellite(satellite)
    
    # 创建目标
    target_group = GroundTargetGroup("城市目标")
    
    # 解析目标城市
    target_data = {
        "北京": (39.9, 116.4),
        "上海": (31.2, 121.5),
        "广州": (23.1, 113.3),
        "纽约": (40.7, -74.0),
        "东京": (35.7, 139.8),
        "伦敦": (51.5, -0.1),
        "莫斯科": (55.8, 37.6),
        "悉尼": (-33.9, 151.2)
    }
    
    # 设置目标
    for target_name in args.targets.split(','):
        target_name = target_name.strip()
        
        if target_name in target_data:
            lat, lon = target_data[target_name]
            target = GroundTarget(target_name, lat, lon)
            target_group.add_target(target)
        else:
            print(f"警告: 未知目标城市 '{target_name}'，将被忽略")
    
    # 如果没有有效目标，添加默认目标
    if len(target_group.targets) == 0:
        print("没有有效目标，使用北京作为默认目标")
        target = GroundTarget("北京", 39.9, 116.4)
        target_group.add_target(target)
    
    # 打印创建的星座和目标信息
    print("已创建卫星星座:")
    for i, satellite in enumerate(constellation.satellites):
        print(f"  {i+1}. {satellite}")
        for sensor in satellite.sensors:
            print(f"     - {sensor}")
            
    print("\n已创建地面目标:")
    for i, target in enumerate(target_group.targets):
        print(f"  {i+1}. {target}")
    
    # 设置分析时间窗口
    start_time = current_time
    end_time = start_time + TimeDelta(args.days * u.day)
    
    # 计算访问窗口
    print(f"\n计算从 {start_time.iso} 到 {end_time.iso} 的访问窗口...")
    access_results = AccessCalculator.calculate_constellation_access(
        constellation, 
        target_group, 
        start_time, 
        end_time,
        step=args.step * u.s
    )
    
    # 打印访问窗口结果
    print("\n访问窗口分析结果:")
    for satellite, target_results in access_results:
        print(f"\n卫星: {satellite.name}")
        
        for target, windows in target_results:
            print(f"  目标: {target.name}")
            
            if not windows:
                print("    无访问窗口")
            else:
                total_access_time = sum((w.end_time - w.start_time).to(u.min).value for w in windows)
                print(f"    总访问时间: {total_access_time:.2f} 分钟")
                print(f"    访问窗口次数: {len(windows)}")
                
                for i, window in enumerate(windows[:3]):  # 只显示前三个窗口
                    duration = (window.end_time - window.start_time).to(u.min).value
                    print(f"    窗口 {i+1}: {window.start_time.iso} 至 {window.end_time.iso} (持续时间: {duration:.2f} 分钟)")
                
                if len(windows) > 3:
                    print(f"    ... 还有 {len(windows) - 3} 个窗口")
    
    # 可视化结果
    print("\n生成可视化结果...")
    visualizer = ConstellationVisualizer()
    fig = visualizer.plot_access_results(access_results, start_time, end_time)
    
    # 显示图形
    try:
        fig.show()
        print("可视化结果已显示。")
    except Exception as e:
        print(f"无法显示图形: {e}")
        print("请确保在支持图形显示的环境中运行。")
    
    return 0


if __name__ == "__main__":
    # sys.exit(main())